# -*- coding: utf-8 -*-

# https://blog.csdn.net/weixin_44777680/article/details/119329911
#pip install alibabacloud_alidns20150109==2.0.2

access_key_id: "xx"
access_key_secret: "xx"


import sys
from typing import List
from loguru import logger
import time
import requests
import re
from alibabacloud_alidns20150109.client import Client as Alidns20150109Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_alidns20150109 import models as alidns_20150109_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

"""
logger.debug()
logger.info()
logger.warning()
logger.error()
logger.info()
logger.success()
logger.critical()
"""
logger.add('my_log.log')

mydomain ='xx.com'
mydomain_rr = 'test'
def create_client(access_key_id: "xx",access_key_secret: "xx",) -> Alidns20150109Client:
    config = open_api_models.Config(
        # 您的 AccessKey ID,
        access_key_id=access_key_id,
        # 您的 AccessKey Secret,
        access_key_secret=access_key_secret
    )
    # 访问的域名
    config.endpoint = f'alidns.cn-beijing.aliyuncs.com'
    return Alidns20150109Client(config)

#获取阿里云上的ip
def getaliyunip():
    client = create_client("xx", "xx")
    describe_sub_domain_records_request = alidns_20150109_models.DescribeSubDomainRecordsRequest(sub_domain=mydomain)
    runtime = util_models.RuntimeOptions()
    try:
        value = client.describe_sub_domain_records_with_options(describe_sub_domain_records_request, runtime)
        #print(value)
        aliyunip = alex_data(value)

        wanip1 = check_ip_way1()
        wanip2 = check_ip_way1()

        if wanip1 != 0 and wanip1 == wanip2:
            if aliyunip[0] == wanip1:
                logger.info("比对ip一致，不执行修改")
            else:
                logger.info("比对ip不一致，执行修改")
                changealyunip(wanip1,aliyunip[1])
        else:
            time.sleep(5)
            logger.error("获取的外网ip不一致,不操作")



    except Exception as error:
        # 如有需要，请打印 error
        UtilClient.assert_as_string(error.message)
        print("报错：")
        logger.error(["报错",UtilClient.assert_as_string(error.message)])


#获取外网ip
def check_ip_way1():
    #http: // pv.sohu.com / cityjson?ie = utf - 8
    #myip.ipip.net
    #cip.cc

    #way1
    getdata = requests.get("http://pv.sohu.com/cityjson?ie=utf-8")
    if getdata.status_code == 200:
        getip = getdata.text[28:getdata.text.find(",")-1]
        logger.info(getip)
        r = '^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$'
        if re.match(r, getip):
            return getip
        else:
            logger.error("getip is bad  way1 ")
            return 0
    else:
        logger.error("url is bad  way1 ")
        return 0
def check_ip_way2():
    #http: // pv.sohu.com / cityjson?ie = utf - 8
    #myip.ipip.net
    #cip.cc

    #way2
    getdata = requests.get("http://myip.ipip.net")
    if getdata.status_code == 200:
        getip = getdata.text[6:getdata.text.find("来自于")-2]
        logger.info(getip)
        r = '^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5]).(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$'
        if re.match(r, getip):
            return getip
        else:
            logger.error("getip is bad  way2 ")
            return 0
    else:
        logger.error("url is bad  way2 ")
        return 0



#更改阿里云域名解析ip
def changealyunip(ip,record_id):
    client = create_client("xx", "xx")
    update_domain_record_request = alidns_20150109_models.UpdateDomainRecordRequest(
        rr=mydomain_rr,
        type='A',
        value=ip,
        record_id=record_id

    )
    runtime = util_models.RuntimeOptions()
    try:
        value = client.update_domain_record_with_options(update_domain_record_request, runtime)
        if value.body.record_id == record_id:
            logger.info(["修改成功",record_id])
        else:
            logger.error("修改不成功，可能存在")

    except Exception as error:
        UtilClient.assert_as_string(error.message)
        logger.error(["修改报错",UtilClient.assert_as_string(error.message)])

# 解析出查询结果中的ip和id，
def alex_data(value):
    #该域名解析条数
    total_count_record = value.body.total_count
    if total_count_record == 1:
        body_data = value.body.domain_records.record[0]
        ip = body_data.value
        record_id = body_data.record_id
        logger.info([ip,record_id])
        return ([ip,record_id])
    else:
        logger.error("no total_count_record value,no ip and record_id")
        return(0)

def main():
    getaliyunip()


if __name__ == '__main__':
    main()

